<template>
  <div class="gate-tasks gradient">
    <div class="banner" v-if="hasPending">
      <el-icon><WarningFilled /></el-icon>
      <span>今日还有未完成任务，请优先完成学习与测试。</span>
    </div>
    <div class="header glass-bar">
      <h2>今日任务</h2>
      <div class="actions-top">
        <el-button @click="load" type="primary" plain>刷新</el-button>
      </div>
    </div>
    <div v-if="loading" class="loading">加载中…</div>
    <div v-else>
      <div v-if="items.length===0" class="empty">暂无任务，返回首页</div>
      <el-card v-for="it in items" :key="it.id" class="task-item glass">
        <div class="row">
          <div>单元ID：{{ it.unitId }}</div>
          <div>阈值：{{ it.passScore }}</div>
          <div>当前分：{{ it.score ?? '-' }}</div>
          <div>状态：<el-tag :type="it.status===1?'success':'warning'">{{ it.status===1?'已完成':'待办' }}</el-tag></div>
        </div>
        <div class="actions">
          <el-button type="primary" :loading="jumping" :disabled="jumping" @click="goLearn('memory', it)">记忆</el-button>
          <el-button type="primary" :loading="jumping" :disabled="jumping" @click="goLearn('dictation', it)">听写</el-button>
          <el-button type="primary" :loading="jumping" :disabled="jumping" @click="goLearn('writing', it)">默写</el-button>
          <el-button type="success" :disabled="!it.canTest || jumping" :loading="jumping" @click="goTest(it)">去测试</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import TASK_API, { type TaskItemVO } from '@/api/dcyx/task.api'
import { useDcyxUnitStoreHook } from '@/store/modules/dcyx_unit.store'
import { useDcyxUserStoreHook } from '@/store/modules/dcyx_user.store'
import { WarningFilled } from '@element-plus/icons-vue'

const router = useRouter()
const items = ref<TaskItemVO[]>([])
const loading = ref(false)
const jumping = ref(false)
const unitStore = useDcyxUnitStoreHook()
const userStore = useDcyxUserStoreHook()
const hasPending = ref(false)

async function load(){
  loading.value = true
  try{
    items.value = await TASK_API.getToday()
    const gate = await TASK_API.getGateTodayStatus()
    hasPending.value = !!gate?.hasPending
  }finally{ loading.value = false }
}

async function goLearn(type:'memory'|'dictation'|'writing', it: TaskItemVO){
  const map: Record<string,string> = {
    memory: '/dcyx/inteli-memory',
    dictation: '/dcyx/inteli-dictation',
    writing: '/dcyx/inteli-writing',
  }
  try{
    jumping.value = true
    // 打通选中单元：更新当前用户的选中 unit
    const uid = Number(userStore.userInfo.id || 0)
    if(uid && it.unitId){
      await unitStore.updateCurrentUnit({ userId: uid, unitId: it.unitId })
    }
    localStorage.setItem('LAST_TASK_ITEM_ID', String(it.id))
    await router.push(map[type])
  } finally {
    jumping.value = false
  }
}

async function goTest(it: TaskItemVO){
  if(!it.canTest || jumping.value) return
  try{
    jumping.value = true
    const uid = Number(userStore.userInfo.id || 0)
    if(uid && it.unitId){
      await unitStore.updateCurrentUnit({ userId: uid, unitId: it.unitId })
    }
    localStorage.setItem('LAST_TASK_ITEM_ID', String(it.id))
    await router.push(`/work/test-paper/${it.unitId}`)
  } finally {
    jumping.value = false
  }
}

// 学习/测试返回后自动刷新
window.addEventListener('focus', async ()=>{
  const lastId = Number(localStorage.getItem('LAST_TASK_ITEM_ID')||'0')
  if(lastId){
    await TASK_API.refreshItem(lastId)
    await load()
  }
})

onMounted(load)
</script>

<style scoped>
.gate-tasks { padding: 16px; min-height: 100vh; }
.gradient{ background: linear-gradient(120deg,#f1f5ff 0%,#f8fbff 60%,#eff3ff 100%); }
.glass{ backdrop-filter: blur(8px); background: rgba(255,255,255,.6); box-shadow: 0 10px 30px rgba(40,80,140,.08); border-radius: 12px; }
.glass-bar{ display:flex; align-items:center; justify-content:space-between; padding: 12px 16px; margin-bottom: 12px; }
.banner{ display:flex; align-items:center; gap:8px; color:#a86a00; background: rgba(255,215,150,.35); border:1px solid rgba(255,180,80,.35); padding:8px 12px; border-radius:10px; margin-bottom:10px }
.header h2{ margin:0; background:linear-gradient(90deg,#4e74ff,#8a8dff); -webkit-background-clip:text; background-clip:text; color:transparent }
.task-item{ margin-bottom:12px; padding: 12px }
.row{ display:flex; gap:16px; align-items:center; margin-bottom:8px }
.actions{ display:flex; gap:8px }
.empty{ color:#888; }
.loading{ color:#666 }
</style>
